
#include <iostream>
#include <fstream>
#include "definitions.h"
#include "log.h"
#include "timestamp.h"
#include "stringutil.h"

void log( const std::string& message, const int& type, bool stderr ) {
	std::string file;
	std::ofstream write;

	if ( stderr )
		std::cerr << "Logged at " << Timestamp::Instance().getDateTime() << ":  " << message << '\n';

	switch ( type ) {
		case SERVER:	file = SERVER_LOG;	break;
		case WORLD:		file = WORLD_LOG;	break;
		case EVENT:		file = EVENT_LOG;	break;
		case ACTION:	file = ACTION_LOG;	break;
		case ACCOUNT:	file = ACCOUNT_LOG;	break;
		case OMNINET:	file = OMNINET_LOG;	break;
		default:		file = DEFAULT_LOG;	break;
	}

	write.open( file.c_str(), std::ofstream::app );
	if ( write.fail() ) {
		default_log( message, file );
	} else {
		write << Timestamp::Instance().getDateTime() << "\n\t" << message << "\n\n";
	}

	write.close();
	write.clear();

	return;
}

void default_log( const std::string& message, const std::string& file ) {
	// default_log is only used in case another log file can't be opened
	std::string error;

	error	<< "default_log():\n"
			<< "\tCouldn't open: " << file << "\n"
			<< "\tTimestamp: " << Timestamp::Instance().getDateTime() << "\n"
			<< "\tMessage: " << message << "\n";
	std::cerr << error;

	std::ofstream write( DEFAULT_LOG, std::ofstream::app );

	if ( write.fail() ) {
		std::cerr << "default_log() couldn't open " << DEFAULT_LOG << " for appending.\n";
	} else {
		write << Timestamp::Instance().getDateTime() << '\n' << error << '\n';
	}

	write.close();
	write.clear();

	return;
}
